package com.example.jetpack_databinding.main7

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

class ScoreViewModel(
    var aTeamScore: MutableLiveData<Int> = MutableLiveData(),
    var bTeamScore: MutableLiveData<Int> = MutableLiveData()
) : ViewModel() {
    init {
        aTeamScore.value = 0
        bTeamScore.value = 0
    }

    var ateamlastScore = 0
    var bteamlastScore = 0

    fun getaTeamScore(): MutableLiveData<Int> {
        if (aTeamScore == null) {
            aTeamScore = MutableLiveData()
            aTeamScore!!.value = 0
        }
        return aTeamScore!!
    }

    fun getbTeamScore(): MutableLiveData<Int> {
        if (bTeamScore == null) {
            bTeamScore = MutableLiveData()
            bTeamScore!!.value = 0
        }
        return bTeamScore!!
    }

    fun aTeamAddScore(i: Int) {
        saveLastScore()
        aTeamScore.value = aTeamScore.value?.plus(i)
    }

    fun bTeamAddScore(i: Int) {
        saveLastScore()
        bTeamScore.value = bTeamScore.value?.plus(i)
    }

    //撤销
    fun undo() {
        aTeamScore.value = ateamlastScore
        bTeamScore.value = bteamlastScore
    }

    //记录上一次分数
    fun saveLastScore() {
        if (aTeamScore.value != null) {
            ateamlastScore = aTeamScore.value!!
        }
        if (bTeamScore.value != null) {
            bteamlastScore = bTeamScore.value!!
        }
    }

    //重置
    fun reset() {
        aTeamScore.value = 0
        bTeamScore.value = 0
    }
}